package com.xiaobias.distributed.pan.web.file;

import com.xiaobias.distributed.pan.service.BaiduPanFileService;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping({"/baidu/pan/file/upload"})
public class BaiduPanUploadController {
    @Resource
    private BaiduPanFileService baiduPanFileService;

    @RequestMapping({"upload.html"})
    public ModelAndView filePage(ModelAndView modelAndView) {
        modelAndView.setViewName("/pan/file/upload");
        return modelAndView;
    }

    @RequestMapping({"upload"})
    @ResponseBody
    public String uploadFile(String panDir, String localFiles) {
        String res = this.baiduPanFileService.uploadFile(panDir, localFiles);
        return res;
    }

    @RequestMapping({"getSererFiles"})
    @ResponseBody
    public Set<String> getSererFiles(@RequestParam(defaultValue = "/root/") String dir) {
        return this.baiduPanFileService.loopFiles(dir);
    }



    // 设置允许访问的根目录（安全措施）
    private final String BASE_DIR = "/";

    /**
     * 获取文件系统节点
     * @param path 请求路径，默认为根目录
     */
    @GetMapping("/nodes")
    @ResponseBody
    public List<FsNode> getNodes(@RequestParam(required = false) String path) {
        File currentDir;
        if (StringUtils.isEmpty(path)) {
            currentDir = new File(BASE_DIR);
        } else {
            // 路径安全校验
            if (!path.startsWith(BASE_DIR)) {
                throw new SecurityException("非法路径访问!");
            }
            currentDir = new File(path);
        }

        return Arrays.stream(currentDir.listFiles())
                .filter(f -> !f.getName().startsWith(".")) // 过滤隐藏文件
                .map(f -> new FsNode(
                        f.getAbsolutePath(),
                        f.getName(),
                        f.isDirectory(),
                        f.isDirectory()  // 目录需设置layui的父节点标记
                ))
                .collect(Collectors.toList());
    }

    @Data
    @AllArgsConstructor
    public static class FsNode {
        private String id;        // 完整路径
        private String name;      // 文件/目录名
        private Boolean isDir;    // 是否为目录
        private Boolean isParent; // Layui树形所需属性
    }
}